#include "lab_main.h"
#include "ui_lab_main.h"

#include "pub_var.h"
#include <QSettings>
#include <QMessageBox>
#include <QSqlError>

Lab_main::Lab_main(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Lab_main)
{
    ui->setupUi(this);

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/lab_main_win").toRect();
    this->setGeometry(rct);
    ui->tabWidget->setCurrentIndex(0);
    ui->le_his_code->setVisible(false);
    ui->le_his_name->setVisible(false);
    ui->pb_save_ord->setEnabled(false);
    ui->le_item_code_rule->setVisible(false);
    ui->le_searial_no->setVisible(false);

    //ui->tab_group->setVisible(false);
    //ui->tab_group->setEnabled(false);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);
    md_dict = new QSqlQueryModel(this);
    md_value = new QSqlQueryModel(this);
    md_mac = new QSqlQueryModel(this);
    md_mac_item = new QSqlQueryModel(this);
    md_group_list = new QSqlQueryModel(this);
    md_group_item = new QSqlQueryModel(this);
    md_pop = new QSqlQueryModel(this);
    md_mac_rule = new QSqlQueryModel(this);
    md_item_rule = new QSqlQueryModel(this);
    md_patient_list = new QSqlQueryModel(this);

    md_input = new QStandardItemModel(this);
    md_input->setColumnCount(5);
    md_input->setHeaderData(0,Qt::Horizontal, "项目名称");
    md_input->setHeaderData(1,Qt::Horizontal, "代码");
    md_input->setHeaderData(2,Qt::Horizontal, "检验结果");
    md_input->setHeaderData(3,Qt::Horizontal, "单位");
    md_input->setHeaderData(4,Qt::Horizontal, "参考值");

    ui->tv_input->setModel(md_input); //

    //dlgt. .editor->    editor->addItem("阴性");

    ui->tv_input->setItemDelegateForColumn(2, &dlgt);
    ui->tv_input->setWordWrap(false); // 文本过长不换行
    ui->tv_input->setEditTriggers(QAbstractItemView::DoubleClicked
                                  | QAbstractItemView::SelectedClicked); // 设置编辑

    tmr = new QTimer(this);

    connect(tmr, &QTimer::timeout, this, &Lab_main::tmr_timeout);

    dlg_get_date = new pub_pop_get_date(this);
    dlg_getItem = new Pub_pop_get_item(this);

    ui->de_fee_0->setDate(QDate::currentDate());

    tmr->start(50);
}

Lab_main::~Lab_main()
{
    delete ui;
}

void Lab_main::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/lab_main_win", QVariant(this->geometry()));

    emit destroyW( "lab_main_win" );

}

void Lab_main::on_pb_close_clicked()
{
    close();
}

void Lab_main::tmr_timeout()
{

    //解决列表宽首次显示不正常问题
    tmr->stop();

    int width;
    if(ui->tabWidget->currentIndex() == 0)
    {
        width = ui->tv_input->width();
        pub::setColumnWidth(ui->tv_input, "0.3^0.1^0.2^0.1^0.2^0^0^0^0^0^", width );
    }
    if(ui->tabWidget->currentIndex() == 1)
    {
        width = ui->tv_dict->width();
        pub::setColumnWidth(ui->tv_dict, "0.8^0^0^0^", width );
    }
    else if(ui->tabWidget->currentIndex() == 2)
    {
        width = ui->tv_machine_list->width();
        pub::setColumnWidth(ui->tv_machine_list, "0.4^0.4^0^0^0^0^0^0^0^", width );
    }
    else if(ui->tabWidget->currentIndex() == 3)
    {
        width = ui->tv_group_list->width();
        pub::setColumnWidth(ui->tv_group_list, "0.4^0.4^0^0^0^0^0^0^0^", width );
    }
    else if( ui->tabWidget->currentIndex() == 4)
    {
        width = ui->tv_machine_list_rule->width();
        pub::setColumnWidth(ui->tv_machine_list_rule, "0.4^0.4^0^0^0^0^0^0^0^", width );
    }

}

void Lab_main::on_tabWidget_tabBarClicked(int index)
{

    //int width = 0;

    if(index == 0)
    {

       // on_pb_list_patient_clicked();

        // 设置列字段名


    }
    else if(index == 1)
    {
        sq = "select name 字典列表, mark from com_dict_com "
             " where dic_type = 'lab_dic' order by ord";

        md_dict->setQuery(sq, pub::db_m);
        ui->tv_dict->setModel(md_dict);

    }
    else if(index == 2 )
    {
        clear_base();

        sq = "select name from com_dict_com  where mark = 'lab' and dic_type = '数值单位'";
        pub::fillCombo(ui->cbb_unit_base, sq, -1);
        ui->cbb_unit_base->addItem("");

        sq = "select name 设备, code 型号, mark from com_dict_com "
             " where dic_type = '检验设备' order by ord";

        md_mac->setQuery(sq, pub::db_m);
        ui->tv_machine_list->setModel(md_mac);

    }
    else if(index == 3)
    {
        ui->le_group_name->clear();
        ui->le_group_code->clear();
        ui->pb_save_ord->setEnabled(false);

        sq = "select item_name 组套名称, item_code 代码 "
             " from fin_com_undruginfo "
             " where valid_state = '1' "
             " and unitflag = '1'"
             " and exedept_code = '%1'"
             " order by item_name";

        sq = sq.arg(pub::dp_code);

        md_group_list->setQuery(sq, pub::db_o);
        ui->tv_group_list->setModel(md_group_list);
    }
    else if( index == 4)
    {
        clear_rule();
        ui->le_machine_code_rule->clear();
        ui->le_machine_name_rule->clear();

        sq = "select name from com_dict_com  where mark = 'lab' and dic_type = '标本类型'";
        pub::fillCombo(ui->cbb_sample_rule, sq, -1);

        sq = "select name 设备, code 型号, mark from com_dict_com "
             " where dic_type = '检验设备' order by ord";

        md_mac_rule->setQuery(sq, pub::db_m);
        ui->tv_machine_list_rule->setModel(md_mac_rule);

    }

    qDebug()<<"页面切换查询 : "<<sq;

    tmr->start(50);

    /*
    QEventLoop ev;
    QTimer::singleShot(100, &ev, SLOT(quit()));
    ev.exec();

    if(ui->tabWidget->currentIndex() == 1)
    {
        width = ui->tv_dict->width();
        pub::setColumnWidth(ui->tv_dict, "0.8^0^0^0^", width );
    }
    else if(ui->tabWidget->currentIndex() == 2)
    {
        width = ui->tv_machine_list->width();
        pub::setColumnWidth(ui->tv_machine_list, "0.4^0.4^0^0^0^0^0^0^0^", width );
    }
    */
}

void Lab_main::on_tv_dict_clicked(const QModelIndex &index)
{
    //保存当前索引，插入新字典数据后，刷新显示时会使用
    mdidx_dict = index;

    QString dic_name = index.siblingAtColumn(0).data(0).toString(); //当前字典名称

    ui->le_name->setText(dic_name);
    //QModelIndex idx = QModelIndex();
    //on_tvValue_clicked(idx);

    sq = "select name 键值, code 代码 , dept_code , ord "
         " from com_dict_com "
         " where mark = 'lab' and dic_type = '"+dic_name+"' ";

    if(ui->rb_code->isChecked())
    {
        sq += " order by ord";
    }else{
        sq += " order by convert(name using gbk)";
    }

    md_value->setQuery(sq, pub::db_m);

    ui->tv_value->setModel(md_value);

    pub::setColumnWidth(ui->tv_value, "0.4^0.4", ui->tv_value->width(), 5 );
}

void Lab_main::on_tv_dict_doubleClicked(const QModelIndex &index)
{
    on_tv_dict_clicked(index);
}

void Lab_main::on_tv_value_clicked(const QModelIndex &index)
{
    QString key = index.siblingAtColumn(0).data(0).toString();
    QString code = index.siblingAtColumn(1).data(0).toString();
    QString ord = index.siblingAtColumn(3).data(0).toString();
    ui->le_key->setText(key);
    ui->le_code->setText(code);
    ui->le_ord->setText(ord);
}

void Lab_main::on_tv_value_doubleClicked(const QModelIndex &index)
{
    on_tv_value_clicked(index);
}

void Lab_main::on_pb_add_clicked()
{
    if(ui->le_name->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "字典名称不允许空缺！");
        return;
    }

    if(ui->le_key->text().trimmed().isEmpty() || ui->le_code->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "字典值的名称和代码不允许空缺！");
        return;
    }

    sq = "select * from com_dict_com where ";
    sq += " dic_type = '" + ui->le_name->text() + "'";
    sq += " and name = '" + ui->le_key->text().trimmed() + "'";
    sq += " and code = '" + ui->le_code->text().trimmed() + "'";
    sq += " and mark = 'lab'";

    qDebug()<<"检查数据是否重复："<<sq;

    qrm->exec(sq);
    if(qrm->next())
    {
        QMessageBox::information(this, "注意", "请检查数据是否重复？");
        return;
    }

    sq = "insert into com_dict_com "
         " (dic_type, name, code, oper_code,oper_time,mark,valid_flag,ord) "
         " values (";
    sq += "'" + ui->le_name->text() + "',";
    sq += "'" + ui->le_key->text().trimmed() + "',";
    sq += "'" + ui->le_code->text().trimmed() + "',";
    sq += "'" + pub::usr_code + "',";
    sq += " now(), 'lab', '1', " + QString::number(ui->le_ord->text().toInt()) ;
    sq += ")";

    qDebug()<<"插入字典数据："<<sq;
    if(qrm->exec(sq))
    {
        ui->le_key->setText("");
        ui->le_code->setText("");
        ui->le_ord->setText("");
    }
    else
    {
        QMessageBox::information(this, "注意", "插入失败，请检查数据是否重复？");
        return;
    }

    on_tv_dict_clicked(mdidx_dict);

}

void Lab_main::on_pb_del_clicked()
{
    if(ui->le_name->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "字典名称不允许空缺！");
        return;
    }

    if(ui->le_key->text().trimmed().isEmpty() || ui->le_code->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "字典值的名称和代码不允许空缺！");
        return;
    }

    sq = "delete from com_dict_com where ";
    sq += " dic_type = '"+ui->le_name->text()+"'";
    sq += " and name = '"+ui->le_key->text().trimmed()+"' ";
    sq += " and code = '"+ui->le_code->text().trimmed()+"' ";
    sq += " and mark = 'lab' ";

    if(qrm->exec(sq)){
        QMessageBox::information(this, "注意", "删除操作成功！");
    }

    on_tv_dict_clicked(mdidx_dict);
    //QModelIndex idx = QModelIndex();
    //on_tvValue_clicked(idx);

    ui->le_key->setText("");
    ui->le_code->setText("");
    ui->le_ord->setText("");
}

void Lab_main::on_pb_add_base_clicked()
{
    if(ui->le_machine_name->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "检验设备名称不允许空缺！");
        return;
    }

    if(ui->le_item_code_mac->text().trimmed().isEmpty()
            || ui->le_item_code_base->text().trimmed().isEmpty()
            || ui->le_item_name_base->text().trimmed().isEmpty()
            )
    {
        QMessageBox::information(this, "注意", "项目的名称、代码、机器代码不允许空缺！");
        return;
    }

    sq = "insert into lis_item "
         " (item_code, item_name, unit, machine_code,"//项目码，项目名，单位，机器编码
         " machine_itemcode,dotsave,caculation," //项目机器码，小数点，计算
         " isprintitem,printnum,"//是否打印, 打印顺序
         " modifypersonid,modifypersonname,modifydate,"//操作员码，操作员名，操作时间
         " his_code, his_name) "//关联的价表项目
         " values (";
    sq += "'" + ui->le_item_code_base->text() + "',";
    sq += "'" + ui->le_item_name_base->text().trimmed() + "',";
    sq += "'" + ui->cbb_unit_base->currentText() + "',";
    sq += "'" + ui->le_machine_code->text() + "',";
    sq += "'" + ui->le_item_code_mac->text().trimmed() + "',";
    sq += "'" + ui->cbb_digit_point->currentText() + "',";
    sq += "'" + ui->le_formular->text().trimmed() + "',";

    QString t = ui->ckb_is_print->isChecked() ? "Y" : "N";
    sq += "'" + t + "',";

    t = QString::number(ui->le_print_ord->text().trimmed().toInt());
    sq += t + ",";

    sq += "'" + pub::usr_code + "',";
    sq += "'" + pub::usr_name + "',";
    sq += " sysdate ," ;

    if(ui->le_price_item_name->text().isEmpty())
    {
        sq += " '','' " ;
    }
    else
    {
        sq += " '" + ui->le_price_item_code->text() + "', " ;
        sq += " '" + ui->le_price_item_name->text() + "' " ;
    }

    sq += ")";

    qDebug()<<"插入lis_item数据："<<sq;
    if(qro->exec(sq))
    {
        //QModelIndex idx = QModelIndex();
        //on_tv_ite value_clicked(idx);
        clear_base();
    }
    else
    {
        QMessageBox::information(this, "注意", "插入失败，请检查数据是否重复，是否有效？");
        return;
    }

//    if(!ui->le_formular->text().trimmed().isEmpty()
//            && !ui->le_price_item_name->text().isEmpty())
//    {
//        //计算公式有录入且关联价表，为计算项目，设置不参与收费标志
//        sq = " update fin_com_undruginfo set special_flag = '0'"
//             " where "
//             " item_code = '" + ui->le_price_item_code->text() + "'";

//        qDebug()<<"设置价表不收费标志："<<sq;
//        if(!qro->exec(sq))
//        {
//            QMessageBox::information(this, "注意", "变更价表收费标志失败？");
//        }
//    }

    on_tv_machine_list_clicked(mdidx_base);
    //QModelIndex idx = QModelIndex();
    //on_tv_value_clicked(idx);


}

void Lab_main::clear_base()
{
    //ui->le_machine_name->clear();
    //ui->le_machine_code->clear();
    ui->le_item_name_base->clear();
    ui->le_item_code_base->clear();
    ui->le_item_code_mac->clear();
    ui->le_formular->clear();
    ui->le_print_ord->clear();
    ui->ckb_is_print->setChecked(true);
    ui->cbb_unit_base->setCurrentIndex(-1);
    ui->cbb_digit_point->setCurrentIndex(0);
    ui->le_price_item_code->clear();
    ui->le_price_item_name->clear();
    ui->le_price_key->clear();
}

void Lab_main::clear_group()
{
    ui->le_item_key->clear();
    ui->le_machine_code_g->clear();
    ui->le_item_name_g->clear();
    ui->le_item_code_g->clear();
    ui->le_ord_in_group->clear();
    ui->pb_save_ord->setEnabled(false);
}

void Lab_main::clear_rule()
{
    //ui->le_machine_name_rule->clear();
    //ui->le_machine_code_rule->clear();
    ui->le_item_name_rule->clear();
    ui->cbb_sample_rule->setCurrentIndex(-1);
    ui->le_unit_rule->clear();
    ui->le_low_restrict->clear();
    ui->le_high_restrict->clear();
    ui->cbb_gend->setCurrentIndex(0);
    ui->le_age_0->clear();
    ui->le_age_1->clear();
    ui->le_searial_no->clear();

}

void Lab_main::on_tv_machine_list_clicked(const QModelIndex &index)
{
    //保存当前索引，插入新字典数据后，刷新显示时会使用
    mdidx_base = index;

    QString mac_name = index.siblingAtColumn(0).data(0).toString();
    QString mac_code = index.siblingAtColumn(1).data(0).toString();

    ui->le_machine_name->setText(mac_name);
    ui->le_machine_code->setText(mac_code);

    sq = "select item_name 项目名称, item_code 代码, machine_code, machine_itemcode, "//0-3
         " unit, dotsave, caculation, isprintitem, printnum,"//4-8
         " modifypersonid, modifypersonname, modifydate, his_code, his_name"//9-13
         " from lis_item "
         " where machine_code = '" + mac_code + "' order by printnum ";

    md_mac_item->setQuery(sq, pub::db_o);

    ui->tv_item_list_base->setModel(md_mac_item);

    pub::setColumnWidth(ui->tv_item_list_base, "0.5^0.3^0^0^0^0^0^0^0^0^0^0^0", ui->tv_item_list_base->width() );
}

void Lab_main::on_tv_machine_list_doubleClicked(const QModelIndex &index)
{
    on_tv_machine_list_clicked(index);
}

void Lab_main::on_tv_item_list_base_clicked(const QModelIndex &index)
{
    //ui->le_machine_name->setText(index.siblingAtColumn(0).data().toString());
    //ui->le_machine_code->setText(index.siblingAtColumn(1).data().toString());
    ui->le_item_name_base->setText(index.siblingAtColumn(0).data().toString());
    ui->le_item_code_base->setText(index.siblingAtColumn(1).data().toString());
    ui->le_item_code_mac->setText(index.siblingAtColumn(3).data().toString());
    ui->le_formular->setText(index.siblingAtColumn(6).data().toString());
    ui->le_print_ord->setText(index.siblingAtColumn(8).data().toString());
    ui->le_price_item_name->setText(index.siblingAtColumn(13).data().toString());
    ui->le_price_item_code->setText(index.siblingAtColumn(12).data().toString());

    if(index.siblingAtColumn(7).data().toString() == "Y")
    {
        ui->ckb_is_print->setChecked(true);
    }
    else
    {
        ui->ckb_is_print->setChecked(false);
    }

    ui->cbb_unit_base->setCurrentText(index.siblingAtColumn(4).data().toString());
    ui->cbb_digit_point->setCurrentText(index.siblingAtColumn(5).data().toString());

}

void Lab_main::on_tv_item_list_base_doubleClicked(const QModelIndex &index)
{
    on_tv_item_list_base_clicked(index);
}

void Lab_main::on_pb_del_base_clicked()
{
    if(ui->le_machine_name->text().trimmed().isEmpty()
            ||ui->le_machine_code->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "检验设备不允许空缺！");
        return;
    }

    if(ui->le_item_code_mac->text().trimmed().isEmpty()
            || ui->le_item_code_base->text().trimmed().isEmpty()
            || ui->le_item_name_base->text().trimmed().isEmpty()
            )
    {
        QMessageBox::information(this, "注意", "项目信息不允许空缺！");
        return;
    }

    sq = "delete from lis_item where ";
    sq += " item_name = '"+ui->le_item_name_base->text()+"'";
    sq += " and item_code = '"+ui->le_item_code_base->text().trimmed()+"' ";
    sq += " and machine_itemcode = '"+ui->le_item_code_mac->text().trimmed()+"' ";

    if(qro->exec(sq)){
        QMessageBox::information(this, "注意", "删除操作成功！");
    }

    on_tv_machine_list_clicked(mdidx_base);
}

void Lab_main::on_tb_reg_0_clicked()
{
    int t = ui->tb_reg_0->pos().y() + this->pos().y();
    int l = ui->tb_reg_0->pos().x() + this->pos().x();

    int w = 0;
    int h = 0;

    dlg_get_date->setDisplay(QRect(l, t, w, h), ui->de_fee_0->date());
    dlg_get_date->setModal(true);
    dlg_get_date->exec();

    ui->de_fee_0->setDate(dlg_get_date->ret_date());
}

void Lab_main::on_pb_list_patient_clicked()
{

    sq = " select distinct "
         " to_char(fee.fee_date,'yyyy-mm-dd') 收费日期, reg.name 患者姓名, " //0-1
         " fee.package_name 项目名称,fee.invoice_no 发票号码, fee.package_code,"//2-4
         " reg.sex_code, (reg.reg_date - reg.birthday)/365.25 age,"//5-6
         " reg.clinic_code, reg.card_no, fee.recipe_no"//7-9
         " from fin_opb_feedetail fee "
         " left join fin_opr_register reg on reg.clinic_code = fee.clinic_code "
         " where trunc(fee.fee_date) = to_date('%1','yyyy-mm-dd') "
         " and pay_flag = '1' "
         " and cancel_flag = '1' "
         " and class_code = 'UL'"
         " and exec_dpcd = '%2'"
         " and reg.name like '%%3%' "
         " and fee.invoice_no like '%%4'"
         " %5"  //confirm status
         " order by fee.invoice_no ";
         //" and fee_date < to_date('%1','yyyy-mm-dd') + 1";

    sq = sq.arg(ui->de_fee_0->date().toString("yyyy-MM-dd"))
            .arg(pub::dp_code)
            .arg(ui->le_patient_name->text().trimmed())
            .arg(ui->le_invoice_no->text().trimmed());

    if(ui->rb_unsaved->isChecked())
    {
        sq = sq.arg(" and confirm_code is null ");
    }
    else
    {
        sq = sq.arg(" and confirm_code is not null ");
    }

    qDebug()<<"提取患者列表："<<sq;

    md_patient_list->setQuery(sq, pub::db_o);
    ui->tv_list_patient->setModel(md_patient_list);
    int width = ui->tv_list_patient->width();
    pub::setColumnWidth(ui->tv_list_patient, "0.22^0.22^0.22^0.22^0^0^0", width);

}

void Lab_main::on_tv_group_list_clicked(const QModelIndex &index)
{
    mdidx_group = index;

    ui->le_group_name->setText(index.siblingAtColumn(0).data().toString());
    ui->le_group_code->setText(index.siblingAtColumn(1).data().toString());

    sq = " select item_name 项目名称, item_code 项目代码 , ext_fld2, his_code, sort_id "
         " from fin_com_undrugztinfo "
         " where "
         " package_code = '" + ui->le_group_code->text() + "' order by sort_id";

    qDebug()<<"提取组套内容："<<sq;

    md_group_item->setQuery(sq, pub::db_o);
    ui->tv_group_item->setModel(md_group_item);
    int width = ui->tv_group_item->width();
    pub::setColumnWidth(ui->tv_group_item, "0.4^0.4^0^0^0^0^0^0^0^", width );

}

void Lab_main::on_tv_group_list_doubleClicked(const QModelIndex &index)
{
    on_tv_group_list_clicked(index);
}

void Lab_main::on_tv_group_item_clicked(const QModelIndex &index)
{
    ui->le_machine_code_g->setText(index.siblingAtColumn(2).data().toString());
    ui->le_item_name_g->setText(index.siblingAtColumn(0).data().toString());
    ui->le_item_code_g->setText(index.siblingAtColumn(1).data().toString());
    ui->le_ord_in_group->setText(index.siblingAtColumn(4).data().toString());

    ui->pb_save_ord->setEnabled(true);

}

void Lab_main::on_tv_group_item_doubleClicked(const QModelIndex &index)
{
    on_tv_group_item_clicked(index);
}

void Lab_main::on_pb_load_group_clicked()
{
    sq = " select machine_code, item_name, item_code, his_code, his_name "
         " from lis_item "
         " where his_code is not null "
         " and item_name like '%" + ui->le_item_key->text().trimmed() + "%' ";

    qDebug()<<"查询化验基础项目 : "<<sq;

    md_pop->setQuery( sq , pub::db_o);

    if(md_pop->rowCount() < 1)
    {
        QMessageBox::information(this, "注意", "找不到符合条件的项目名称，请确认检验基础项目与价表项目已经对照！");
        return;
    }

    dlg_getItem->setDisplay(*md_pop,QRect(300, 150, 800, 500),"","0.2^0.3^0.2^0^0^0^0^0^0^0^0^0^0^0.1^0.3^0^0^0");

    dlg_getItem->setModal(true);
    dlg_getItem->exec();

    QString popRetStr = dlg_getItem->retStr();

    if(popRetStr.isEmpty())
    {
        return;
    }
    qDebug()<<"pop select return value is : "<<popRetStr;

    ui->le_machine_code_g->setText( pub::getStr(popRetStr, "^", 1));
    ui->le_item_name_g->setText( pub::getStr(popRetStr, "^", 2));
    ui->le_item_code_g->setText( pub::getStr(popRetStr, "^", 3));
    ui->le_his_code->setText( pub::getStr(popRetStr, "^", 4));
    ui->le_his_name->setText( pub::getStr(popRetStr, "^", 5));

}

void Lab_main::on_pb_del_group_clicked()
{
    if(ui->le_group_name->text().isEmpty()
            ||ui->le_group_code->text().isEmpty())
    {
        QMessageBox::information(this, "注意", "组套名称不允许空缺！");
        return;
    }

    if(ui->le_machine_code_g->text().isEmpty()
            || ui->le_item_name_g->text().isEmpty()
            || ui->le_item_code_g->text().isEmpty()
            )
    {
        QMessageBox::information(this, "注意", "项目信息不允许空缺！");
        return;
    }

    sq = "delete from fin_com_undrugztinfo where ";
    sq += " item_code = '"+ui->le_item_code_g->text()+"' ";
    sq += " and ext_fld2 = '"+ui->le_machine_code_g->text()+"' ";
    sq += " and package_code = '"+ui->le_group_code->text()+"' ";

    if(qro->exec(sq)){
        QMessageBox::information(this, "注意", "删除操作成功！");
    }

    on_tv_group_list_clicked(mdidx_group);
    calculate_group_price( ui->le_group_code->text() );
    clear_group();
}

void Lab_main::on_pb_add_group_clicked()
{
    if(ui->le_group_name->text().isEmpty()
            ||ui->le_group_code->text().isEmpty())
    {
        QMessageBox::information(this, "注意", "组套名称不允许空缺！");
        return;
    }

    if(ui->le_machine_code_g->text().isEmpty()
            || ui->le_item_name_g->text().isEmpty()
            || ui->le_item_code_g->text().isEmpty()
            )
    {
        QMessageBox::information(this, "注意", "项目信息不允许空缺！");
        return;
    }

    sq = "insert into fin_com_undrugztinfo "
         " (his_code,his_name,"//
         " item_code, item_name, ext_fld2,"//项目码，项目名，机器编码
         " package_name, package_code,"//组套名，组套码
         " sort_id, qty, exe_deptcode, " //组内序号， 数量
         " oper_code, oper_date"//操作员码，操作时间
         " ) values (";
    sq += "'" + ui->le_his_code->text() + "',";
    sq += "'" + ui->le_his_name->text() + "',";
    sq += "'" + ui->le_item_code_g->text() + "',";
    sq += "'" + ui->le_item_name_g->text() + "',";
    sq += "'" + ui->le_machine_code_g->text() + "',";
    sq += "'" + ui->le_group_name->text() + "',";
    sq += "'" + ui->le_group_code->text() + "',";

    int ord = ui->le_ord_in_group->text().toInt();
    sq += QString::number(ord) + ", 1 , ";

    sq += "'" + pub::dp_code + "',";
    sq += "'" + pub::usr_code + "',";
    sq += " sysdate " ;
    sq += ")";

    qDebug()<<"插入 fin_com_undrugztinfo ："<<sq;

    if(qro->exec(sq))
    {
        ui->le_machine_code_g->clear();
        ui->le_item_name_g->clear();
        ui->le_item_code_g->clear();
        ui->le_item_key->clear();
        ui->le_his_code->clear();
        ui->le_his_name->clear();
    }
    else
    {
        QMessageBox::information(this, "注意", "插入失败，请检查数据是否有效？");
        return;
    }

    on_tv_group_list_clicked(mdidx_group);
    calculate_group_price( ui->le_group_code->text() );
    clear_group();
}

void Lab_main::calculate_group_price(QString his_code)
{
    sq = "select sum(fin.unit_price) "
         " from fin_com_undrugztinfo grp"
         " left join lis_item itm on itm.item_code = grp.item_code and itm.machine_code = grp.ext_fld2 "
         " left join fin_com_undruginfo fin on fin.item_code = itm.his_code"
         " where "
         " grp.package_code = '" + his_code + "'";

    qDebug()<<"计算组套价格 ： "<<sq;

    if(!qro->exec(sq))
    {
        QMessageBox::information(this, "Note", "Calculate group price SQL error.");
        qDebug()<<qro->lastError().text();
        return;
    }

    qro->next();

    sq = "update fin_com_undruginfo set unit_price = %1 "
         " where item_code = '%2'";

    sq = sq.arg(qro->value(0).toDouble()).arg(his_code);

    qDebug()<<"修改组套价格 ： "<<sq;
    if(!qro->exec(sq))
    {
        QMessageBox::information(this, "Note", "Update group price SQL error.");
        qDebug()<<qro->lastError().text();
        return;
    }
}

void Lab_main::on_pb_load_price_item_clicked()
{
    sq = "select item_name 项目名称, item_code 项目代码 "
         " from fin_com_undruginfo "
         " where valid_state = '1' and unitflag = '0' "
         " and exedept_code = '%1' "
         " and item_name like '%%2%'";

    sq = sq.arg(pub::dp_code)
            .arg(ui->le_price_key->text().trimmed());

    qDebug()<<"查询关联的执行价表项目 : "<<sq;

    md_pop->setQuery( sq , pub::db_o);

    dlg_getItem->setDisplay(*md_pop,QRect(300, 150, 800, 500),"","0.5^0.4^0^0^0^0^0^0^0^0^0^0^0^0.1^0.3^0^0^0");

    dlg_getItem->setModal(true);
    dlg_getItem->exec();

    QString popRetStr = dlg_getItem->retStr();
    if(popRetStr.isEmpty())
    {
        return;
    }
    qDebug()<<"pop select return value is : "<<popRetStr;

    ui->le_price_item_name->setText(pub::getStr(popRetStr, "^",1));
    ui->le_price_item_code->setText(pub::getStr(popRetStr, "^", 2));
}

void Lab_main::on_pb_item_change_clicked()
{
    if(ui->le_machine_name->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "检验设备名称不允许空缺！");
        return;
    }

    if(ui->le_item_code_mac->text().trimmed().isEmpty()
            || ui->le_item_code_base->text().trimmed().isEmpty()
            || ui->le_item_name_base->text().trimmed().isEmpty()
            )
    {
        QMessageBox::information(this, "注意", "项目的名称、代码、机器代码不允许空缺！");
        return;
    }

    sq = "update lis_item set "
         " unit = '%1', "//单位，
            " machine_itemcode = '%2',"//项目机器码
            " dotsave = '%3',"//小数点
            " caculation = '%4'," //计算
            " isprintitem = '%5',"//是否打印
            " printnum = '%6',"//打印顺序
            " modifypersonid = '%7',"//操作员码
            " modifypersonname = '%8',"//操作员名
            " modifydate = sysdate,"//操作时间
            " his_code = '%9',"//关联的价表项目
            " his_name = '%10' "//关联的价表项目
            " where "
            " item_code = '%11'"//项目码
            " and item_name = '%12'"//项目名称
            " and machine_code = '%13'";//机器编码"

    QString prt = ui->ckb_is_print->isChecked() ? "Y" : "N";
    QString rela_name,rela_code;
    if(ui->le_price_item_code->text().isEmpty())
    {
        rela_name = "" ;
        rela_code = "" ;
    }
    else
    {
        rela_name = ui->le_price_item_name->text();
        rela_code = ui->le_price_item_code->text();
    }

    sq = sq.arg(ui->cbb_unit_base->currentText())//单位，
            .arg(ui->le_item_code_mac->text())//项目机器码
            .arg(ui->cbb_digit_point->currentText())//小数点
            .arg(ui->le_formular->text().trimmed())//计算
            .arg(prt)//是否打印
            .arg(QString::number(ui->le_print_ord->text().trimmed().toInt()))//打印顺序
            .arg(pub::usr_code)//操作员码
            .arg(pub::usr_name)//操作员名
            .arg(rela_code)//关联的价表项目
            .arg(rela_name)//关联的价表项目
            .arg(ui->le_item_code_base->text())//项目码
            .arg(ui->le_item_name_base->text().trimmed())//项目名称
            .arg(ui->le_machine_code->text());//机器编码"

    qDebug()<<"变更 lis_item数据："<<sq;
    if(qro->exec(sq))
    {
        sq = " update fin_com_undrugztinfo "
             " set his_code = '%1' "
             " where ext_fld2 = '%2' "
             " and exe_deptcode = '%3' "
             " and item_code = '%4'";
        sq = sq.arg(rela_code)
                .arg(ui->le_machine_code->text())
                .arg(pub::dp_code)
                .arg(ui->le_item_code_base->text());

        qDebug()<<"修改关联组合项目中的his编码："<<sq;

        if(!qro->exec(sq))
        {
            QMessageBox::information(this, "注意", "修改关联组合项目中的his编码失败！");
            return;
        }

//        if(!ui->le_formular->text().trimmed().isEmpty()
//                && !ui->le_price_item_name->text().isEmpty())
//        {
//            //计算公式有录入且关联价表，为计算项目，设置不参与收费标志
//            sq = " update fin_com_undruginfo set special_flag = '0'"
//                 " where "
//                 " item_code = '" + ui->le_price_item_code->text() + "'";

//            qDebug()<<"设置价表不收费标志："<<sq;
//            if(!qro->exec(sq))
//            {
//                QMessageBox::information(this, "注意", "变更价表收费标志失败？");
//            }
//        }

        clear_base();
    }
    else
    {
        QMessageBox::information(this, "注意", "sql 失败，请检查数据是否重复，是否有效？");
        return;
    }

    on_tv_machine_list_clicked(mdidx_base);

}

void Lab_main::on_pb_save_ord_clicked()
{
    if(ui->le_group_name->text().isEmpty()
            ||ui->le_group_code->text().isEmpty())
    {
        QMessageBox::information(this, "注意", "组套名称不允许空缺！");
        return;
    }

    if(ui->le_machine_code_g->text().isEmpty()
            || ui->le_item_name_g->text().isEmpty()
            || ui->le_item_code_g->text().isEmpty()
            )
    {
        QMessageBox::information(this, "注意", "项目信息不允许空缺！");
        return;
    }

    int ord = ui->le_ord_in_group->text().toInt();

    sq = "update fin_com_undrugztinfo "
         " set sort_id = %1, oper_code = '%2', oper_date = sysdate "
         " where "   ;
    sq += " item_code = '" + ui->le_item_code_g->text() + "'";//项目码
    sq += " and item_name = '" + ui->le_item_name_g->text() + "'";//项目名
    sq += " and ext_fld2 = '" + ui->le_machine_code_g->text() + "'";//机器编码
    sq += " and package_name = '" + ui->le_group_name->text() + "'";//组套名
    sq += " and package_code = '" + ui->le_group_code->text() + "'";//组套码

    sq = sq.arg(QString::number(ord))
            .arg(pub::usr_code);

    qDebug()<<"保存序号 fin_com_undrugztinfo ："<<sq;
    if(qro->exec(sq))
    {
        ui->le_machine_code_g->clear();
        ui->le_item_name_g->clear();
        ui->le_item_code_g->clear();
        ui->le_item_key->clear();
    }
    else
    {
        QMessageBox::information(this, "注意", "sql 失败，请检查数据是否有效？");
        return;
    }

    on_tv_group_list_clicked(mdidx_group);
    clear_group();


}

void Lab_main::on_pb_add_rule_clicked()
{

    if(ui->le_machine_name_rule->text().isEmpty()
            || ui->le_item_name_rule->text().isEmpty()  )
    {
        QMessageBox::information(this, "注意", "设备和项目名称不允许空缺！");
        return;
    }

    bool ok;
    double low = ui->le_low_restrict->text().trimmed().toDouble(&ok);

    if(!ok)
    {
        QMessageBox::information(this, "注意", "下限数据无效！");
        return;
    }

    double high = ui->le_high_restrict->text().trimmed().toDouble(&ok);

    if(!ok)
    {
        QMessageBox::information(this, "注意", "上限数据无效！");
        return;
    }

    if(qFuzzyCompare(low, high) || low > high)
    {
        QMessageBox::information(this, "注意", "参考值数据范围无效！");
        return;
    }

    if(ui->le_age_0->text().isEmpty()
           ^ ui->le_age_1->text().isEmpty() )
    {
        QMessageBox::information(this, "注意", "年龄不完整！");
        return;
    }

    int ag0 = ui->le_age_0->text().trimmed().toInt();
    int ag1 = ui->le_age_1->text().trimmed().toInt();

    if(ag0 > 0 && ag0 > ag1)
    {
        QMessageBox::information(this, "注意", "年龄数值无效！");
        return;
    }

    sq = "select LIS_SEQITEMRULES.nextval from dual";
    qro->exec(sq);
    qro->next();
    QString serial_no = qro->value(0).toString();

    sq = "insert into lis_itemrules ("
         " item_code, item_name, maxlevel,minlevel,searialno,"
         " agedown,ageup,sex,machine_code,sample_type,unit "
         " ) values (";
    sq += "'" + ui->le_item_code_rule->text() + "',";
    sq += "'" + ui->le_item_name_rule->text() + "',";
    sq += "'" +ui->le_high_restrict->text() + "',";
    sq += "'" +ui->le_low_restrict->text() + "',";
    sq += "'" + serial_no + "',";
    sq += "'" + ui->le_age_0->text() + "',";
    sq += "'" + ui->le_age_1->text() + "',";
    sq += "'" + ui->cbb_gend->currentText() + "',";
    sq += "'" + ui->le_machine_code_rule->text() + "',";
    sq += "'" + ui->cbb_sample_rule->currentText() + "',";
    sq += "'" + ui->le_unit_rule->text() + "'";
    sq += ")";

    qDebug()<<"插入规则："<<sq;

    if(!qro->exec(sq))
    {
        QMessageBox::information(this, "注意", "保存规则失败，请检查数据是否有效？");
        return;
    }


    on_tv_machine_list_rule_clicked(mdidx_rule);
}

void Lab_main::on_tv_machine_list_rule_clicked(const QModelIndex &index)
{
    //保存当前索引，插入新字典数据后，刷新显示时会使用
    mdidx_rule = index;

    QString mac_name = index.siblingAtColumn(0).data(0).toString();
    QString mac_code = index.siblingAtColumn(1).data(0).toString();

    ui->le_machine_name_rule->setText(mac_name);
    ui->le_machine_code_rule->setText(mac_code);

    sq = "select item_name 项目名称, item_code 代码, sex 性别, agedown ||'-'|| ageup 年龄 , "//0-3
         " unit, sample_type, minlevel, maxlevel, agedown, ageup ,searialno "//4-10
         " from lis_itemrules "
         " where machine_code = '" + mac_code + "' order by item_name ";

    qDebug()<<"提取设备关联的规则："<<sq;

    md_item_rule->setQuery(sq, pub::db_o);

    ui->tv_item_list_rule->setModel(md_item_rule);

    pub::setColumnWidth(ui->tv_item_list_rule, "0.35^0.2^0.1^0.2^0^0^0^0^0^0^0^0", ui->tv_item_list_rule->width() );

    clear_rule();
}

void Lab_main::on_tv_machine_list_rule_doubleClicked(const QModelIndex &index)
{
    on_tv_machine_list_rule_clicked(index);
}


void Lab_main::on_pb_get_item_rule_clicked()
{
    sq = " select machine_code, item_name, item_code, unit"
         " from lis_item "
         " where machine_code = '" + ui->le_machine_code_rule->text().trimmed() + "' ";
         //" and "
         //" and item_name like '%" + ui->le_item_key->text().trimmed() + "%' ";

    qDebug()<<"查询化验基础项目 : "<<sq;

    md_pop->setQuery( sq , pub::db_o);

    if(md_pop->rowCount() < 1)
    {
        QMessageBox::information(this, "注意", "找不到符合条件的项目名称，请确认检验基础项目与价表项目已经对照！");
        return;
    }

    dlg_getItem->setDisplay(*md_pop,QRect(300, 150, 800, 500),"","0.2^0.3^0.2^0^0^0^0^0^0^0^0^0^0^0.1^0.3^0^0^0");

    dlg_getItem->setModal(true);
    dlg_getItem->exec();

    QString popRetStr = dlg_getItem->retStr();

    if(popRetStr.isEmpty())
    {
        return;
    }
    qDebug()<<"pop select return value is : "<<popRetStr;

    ui->le_item_name_rule->setText( pub::getStr(popRetStr, "^", 2));
    ui->le_item_code_rule->setText( pub::getStr(popRetStr, "^", 3));
    ui->le_unit_rule->setText( pub::getStr(popRetStr, "^", 4));
    //ui->le_his_name->setText( pub::getStr(popRetStr, "^", 5));
}

void Lab_main::on_tv_item_list_rule_clicked(const QModelIndex &index)
{
    ui->le_item_name_rule->setText( index.siblingAtColumn(0).data().toString());
    ui->le_item_code_rule->setText( index.siblingAtColumn(1).data().toString());
    ui->le_unit_rule->setText( index.siblingAtColumn(4).data().toString());

    ui->cbb_sample_rule->setCurrentText(index.siblingAtColumn(5).data().toString());
    ui->le_low_restrict->setText( index.siblingAtColumn(6).data().toString());
    ui->le_high_restrict->setText( index.siblingAtColumn(7).data().toString());

    ui->cbb_gend->setCurrentText( index.siblingAtColumn(2).data().toString());
    ui->le_age_0->setText( index.siblingAtColumn(8).data().toString());
    ui->le_age_1->setText( index.siblingAtColumn(9).data().toString());

    ui->le_searial_no->setText( index.siblingAtColumn(10).data().toString());
}

void Lab_main::on_pb_del_rule_clicked()
{
    if(ui->le_searial_no->text().isEmpty())
    {
        QMessageBox::information(this, "注意", "未选定项目！");
        return;
    }

    sq = "delete from lis_itemrules where searialno = '" + ui->le_searial_no->text() + "'";
    qro->exec(sq);

    on_tv_machine_list_rule_clicked(mdidx_rule);

}

void Lab_main::on_pb_item_change_rule_clicked()
{
    if(ui->le_searial_no->text().isEmpty())
    {
        QMessageBox::information(this, "注意", "未选定项目！");
        return;
    }

    sq = " update lis_itemrules set ";
    sq += " item_code = '" + ui->le_item_code_rule->text() + "',";
    sq += " item_name = '" + ui->le_item_name_rule->text() + "',";
    sq += " maxlevel = " + ui->le_high_restrict->text() + ",";
    sq += " minlevel = " + ui->le_low_restrict->text() + ",";
    sq += " agedown = '" + ui->le_age_0->text() + "',";
    sq += " ageup = '" + ui->le_age_1->text() + "',";
    sq += " sex = '" + ui->cbb_gend->currentText() + "',";
    sq += " sample_type = '" + ui->cbb_sample_rule->currentText() + "'";
    sq += " where searialno = '" + ui->le_searial_no->text() + "'";

    if(!qro->exec(sq))
    {
        QMessageBox::information(this, "注意", "保存规则失败，请检查数据是否有效？");
        return;
    }

    on_tv_machine_list_rule_clicked(mdidx_rule);

}

void Lab_main::on_pb_clear_clicked()
{
    ui->le_invoice_no->clear();
    ui->le_patient_name->clear();
    ui->pt_result->clear();

    if(md_input->rowCount() > 0)
    {
        md_input->removeRows(0, md_input->rowCount());
    }
}

void Lab_main::on_tv_list_patient_clicked(const QModelIndex &index)
{

    on_pb_clear_clicked();
    patient_info.clear();

    patient_info["package_code"] = index.siblingAtColumn(4).data().toString();

    if(index.siblingAtColumn(5).data().toString() == "M")
    {
        patient_info["gend"] = "男";
    }
    else
    {
        patient_info["gend"] = "女";
    }

    patient_info["age"] = index.siblingAtColumn(6).data().toString();
    patient_info["clinic_code"] = index.siblingAtColumn(7).data().toString();
    patient_info["card_no"] = index.siblingAtColumn(8).data().toString();
    patient_info["recipe_no"] = index.siblingAtColumn(9).data().toString();
    patient_info["package_code"] = index.siblingAtColumn(4).data().toString();
    patient_info["package_name"] = index.siblingAtColumn(2).data().toString();
    patient_info["invoice_no"] = index.siblingAtColumn(3).data().toString();

    sq = " select grp.sort_id,grp.ext_fld2," //打印序号， 检验设备
         " grp.his_code, grp.his_name,"//his
         " grp.package_code, grp.package_name,"//package/group
         " grp.item_code,grp.item_name,"//项目在设备中的编码和名称
         " rule.sample_type, "//标本
         " rule.agedown,rule.ageup,"//年龄范围
         " rule.sex,rule.unit,"
         " rule.maxlevel,rule.minlevel,"//标准值范围
         " rule.minlevel || '-' || rule.maxlevel range"//标准值范围
         " from fin_com_undrugztinfo grp"
         " left join lis_itemrules rule "
         "   on rule.machine_code = grp.ext_fld2 "
         "   and rule.item_code = grp.item_code"
         " where "
         " grp.package_code = '%1'"
         " and grp.sort_id <> '0'"  //
         " and (rule.sex is null or rule.sex = '%2') " //不区分性别，或性别符合
         " and ("
         "        ( rule.agedown is null and rule.ageup is null ) "//不区分年龄，或年龄符合
         "        or "
         "        ( to_number(rule.ageup) >= %3  "      //年龄判定方法：大于下限，小于等于上限
         "             and to_number(rule.agedown) < %3"
         "        )"
         "      )"
         " order by grp.sort_id";

    sq = sq.arg(patient_info["package_code"])
            .arg(patient_info["gend"])
            .arg(patient_info["age"]);

    qDebug()<<"提取关联的检验明细项目01："<<sq;

    qro->exec(sq);

    if(!qro->next())
    {
        //非化验室组套

        sq = " select grp.sort_id,grp.ext_fld2," //打印序号， 检验设备
                " grp.his_code, grp.his_name,"//his
                " grp.package_code, grp.package_name,"//package/group
                " grp.item_code,grp.item_name,"//项目在设备中的编码和名称
                " rule.sample_type, "//标本
                " rule.agedown,rule.ageup,"//年龄范围
                " rule.sex,rule.unit,"
                " rule.maxlevel,rule.minlevel,"//标准值范围
                " rule.minlevel || '-' || rule.maxlevel range"//标准值范围
                " from "
                "  (select 0 sort_id, itm.machine_code ext_fld2,"
                "   '%1' his_code, '%4' his_name,"
                "   '%1' package_code, '%4' package_name,"
                "   itm.item_code, itm.item_name"
                "   from lis_item itm "
                "   where itm.his_code = '%1') grp "
                " left join lis_itemrules rule "
                "   on rule.machine_code = grp.ext_fld2 "
                "   and rule.item_code = grp.item_code"
                " where "
                " (rule.sex is null or rule.sex = '%2') " //不区分性别，或性别符合
                " and ("
                "        ( rule.agedown is null and rule.ageup is null ) "//不区分年龄，或年龄符合
                "        or "
                "        ( to_number(rule.ageup) > %3  "
                "             and to_number(rule.agedown) < %3"
                "        )"
                "      )"
                " order by grp.sort_id";

        sq = sq.arg(patient_info["package_code"])
                .arg(patient_info["gend"])
                .arg(patient_info["age"])
                .arg(patient_info["package_name"]);

        qDebug()<<"提取关联的检验明细项目02："<<sq;

        qro->exec(sq);
        if(!qro->next())
        {
            QMessageBox::information(this, "注意", "检验项目信息无效！");
            return;
        }
    }

    patient_info["package_name"] = qro->value("package_name").toString();


    if(ui->rb_saved->isChecked())
    {
        sq = "select lisitem_result, lis_summary from met_chk_lis_result"
             " where seq_no = '%1'"
             " and package_code = '%2' "
             " order by lis_item_printsort ";

        sq = sq.arg(patient_info["recipe_no"])
                .arg(patient_info["package_code"]);

        qDebug()<<"读取已经保存过的数据："<<sq;

        qrot->exec(sq);
        qrot->next();

        ui->pt_result->setPlainText(qrot->value(1).toString());
    }

    for(int row = 0; ; row++)
    {

        md_input->setItem(row, 0, new QStandardItem(qro->value("item_name").toString()));
        md_input->setItem(row, 1, new QStandardItem(qro->value("item_code").toString()));

        if(ui->rb_unsaved->isChecked())
        {
            md_input->setItem(row, 2, new QStandardItem(""));
        }
        else
        {
            QString v = qrot->value(0).toString();
            qDebug()<<"saved value : "<<v;
            md_input->setItem(row, 2, new QStandardItem(v));
        }
        md_input->setItem(row, 3, new QStandardItem(qro->value("unit").toString()));
        md_input->setItem(row, 4, new QStandardItem(qro->value("range").toString()));

        md_input->item(row, 0)->setFlags(Qt::NoItemFlags);
        md_input->item(row, 1)->setFlags(Qt::NoItemFlags);
        md_input->item(row, 3)->setFlags(Qt::NoItemFlags);
        md_input->item(row, 4)->setFlags(Qt::NoItemFlags);

        if(!qro->next())
        {
            break;
        }

        if(ui->rb_saved->isChecked())
        {
            qrot->next();
        }
    }

    int width = ui->tv_input->width();
    pub::setColumnWidth(ui->tv_input, "0.3^0.1^0.2^0.1^0.2^0^0^0^0^0^", width );

}

void Lab_main::on_tv_list_patient_doubleClicked(const QModelIndex &index)
{
    on_tv_list_patient_clicked(index);
}

void Lab_main::on_pb_save_result_clicked()
{
    if(ui->pt_result->toPlainText().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "检验结论不可以为空！");
        return;
    }

    pub::db_o.transaction();

    qro->first();

    if(ui->rb_saved->isChecked())
    {
        //已经保存过的数据,首先转储保存原始记录

        sq = " insert into met_chk_lis_result_bk"
             " (card_no, clinic_code, hisitem_code, "
             " machine_code, lisitem_code, lisitem_name,"
             " lisitem_result, unit, flag, "
             " downvalue,upvalue, unusual_flag, "
             " lis_summary, lis_item_printsort, "
             " audit_opercode, audit_date, audit_opername,"
             " itemtype,seq_no,range,"
             " package_code,package_name)"
             " select "
             " card_no, clinic_code, hisitem_code, "
             " machine_code, lisitem_code, lisitem_name,"
             " lisitem_result, unit, flag, "
             " downvalue,upvalue, unusual_flag, "
             " lis_summary, lis_item_printsort, "
             " audit_opercode, audit_date, audit_opername,"
             " itemtype,seq_no,range,"
             " package_code,package_name "
             " from met_chk_lis_result "
             " where "
             " seq_no = '%1' "
             " and package_code = '%2' ";

        sq = sq.arg(patient_info["recipe_no"])
                .arg(patient_info["package_code"]);

        qDebug()<<"转储历史记录:"<<sq;
        pub::db_o.exec(sq);

        if(pub::db_o.lastError().isValid())
        {
            QMessageBox::information(this, "注意", "转储历史记录失败！");
            qDebug()<<pub::db_o.lastError().text();

            pub::db_o.rollback();
            return;
        }

        sq = " delete from met_chk_lis_result where "
             " seq_no = '%1' "
             " and package_code = '%2' ";
        sq = sq.arg(patient_info["recipe_no"])
                .arg(patient_info["package_code"]);

        qDebug()<<"清除当前记录："<<sq;

        pub::db_o.exec(sq);

        if(pub::db_o.lastError().isValid())
        {
            QMessageBox::information(this, "注意", "清除当前记录失败！");
            qDebug()<<pub::db_o.lastError().text();
            pub::db_o.rollback();
            return;
        }
    }

    int row = 0;

    while(true)
    {

        //读取录入的结果
        QString item_value = md_input->item(row,2)->text().trimmed();

        if(item_value.isEmpty())
        {
            QMessageBox::information(this, "注意", "检验项目数值不允许为空！");
            pub::db_o.rollback();
            return;
        }

        sq = " insert into met_chk_lis_result"
             " (card_no, clinic_code, hisitem_code, "
             " machine_code, lisitem_code, lisitem_name,"
             " lisitem_result, unit, flag, "
             " downvalue,upvalue, unusual_flag, "
             " lis_summary, lis_item_printsort, "
             " audit_opercode, audit_date, audit_opername,"
             " itemtype,seq_no,range,"
             " package_code,package_name)"
             " values( "
             " '%1', '%2', '%3', '%4', '%5',"
             " '%6', '%7', '%8', '%9', %10,"
             " %11, '%12', '%13', %14, '%15',"
             " sysdate, '%16', '%17', '%18', '%19',"
             " '%20', '%21')";

        QString down_value = qro->value("minlevel").toString();

        if(down_value.isEmpty())
        {
            down_value = "0";
        }

        QString up_value = qro->value("maxlevel").toString();

        if(up_value.isEmpty())
        {
            up_value = "0";
        }

        sq = sq.arg(patient_info["card_no"]) //card_no
                .arg(patient_info["clinic_code"]) //clinic_code
                .arg(qro->value("his_code").toString()) //hisitem_code
                .arg(qro->value("ext_fld2").toString()) //machine_code
                .arg(qro->value("item_code").toString()) //lisitem_code
                .arg(qro->value("item_name").toString()) //lisitem_name
                .arg(item_value) //lisitem_result
                .arg(qro->value("unit").toString()) //unit
                .arg("") //flag
                .arg(down_value ) //downvalue
                .arg(up_value) //upvalue
                .arg("") //unusual_flag
                .arg(ui->pt_result->toPlainText().trimmed()) //lis_summary
                .arg(qro->value("sort_id").toString()) //lis_item_printsort
                .arg(pub::usr_code) //audit_opercode
                .arg(pub::usr_name) //audit_opername
                .arg("") //itemtype
                .arg(patient_info["recipe_no"]) //seq_no
                .arg(qro->value("range").toString()) //range
                .arg(patient_info["package_code"]) //package_code
                .arg(qro->value("package_name").toString()); //package_name

        qDebug()<<"插入检验结果："<<sq;

        pub::db_o.exec(sq);
        if(pub::db_o.lastError().isValid())
        {
            qDebug()<< pub::db_o.lastError().text();
            QMessageBox::information(this, "注意", "插入检验结果失败！");
            pub::db_o.rollback();
            return;
        }

        row++;

        if(!qro->next())
        {
            break;
        }

    }

    pub::db_o.commit();
    QMessageBox::information(this, "注意", "检验数据保存完成！" );

    sq = "update fin_opb_feedetail set confirm_code = '%1' "
         " where recipe_no = '%2'"
         " and package_code = '%3'";

    sq = sq.arg(pub::usr_code)
            .arg(patient_info["recipe_no"])
            .arg(patient_info["package_code"]);

    //    pub::db_o.exec(sq);
    qrot->exec(sq);
    qDebug()<<"fin_opb_feedetail : "<<sq;


    sq = "update ys_bz_e_lib set xmjg = '%1' "
         " where clinic_code = '%2' and xmmc = '%3'";
    sq = sq.arg(ui->pt_result->toPlainText().trimmed())
            .arg(patient_info["clinic_code"])
            .arg(patient_info["package_name"]);

    qDebug()<<"保存数据到 ys_bz_e_lis : "<<sq;

    qrm->exec(sq);

    on_pb_clear_clicked();
    on_pb_list_patient_clicked();
}

void Lab_main::on_rb_unsaved_clicked()
{
    on_pb_clear_clicked();
    md_patient_list->setQuery(NULL);
}

void Lab_main::on_rb_saved_clicked()
{
    on_pb_clear_clicked();
    md_patient_list->setQuery(NULL);
}

